﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace ZMHWcfServiceLibrary
{
    // 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码和配置文件中的类名“PublisherAndSubscriber”。
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class PublisherAndSubscriber : IPublisherAndSubscriber
    {
        public delegate void GenericEventHandler();
        public delegate void GenericEventHandler<T>(T t);
        public delegate void GenericEventHandler<T, U>(T t, U u);

        static GenericEventHandler m_Event1 = delegate { };
        static GenericEventHandler<int> m_Event2 = delegate { };
        static GenericEventHandler<int, string> m_Event3 = delegate { };

        public void Subscribe(EventType mask)
        {
            IPublisherAndSubscriberCallback subscriber = OperationContext.Current.GetCallbackChannel<IPublisherAndSubscriberCallback>();
            if ((mask & EventType.Event1) == EventType.Event1) { m_Event1 += subscriber.OnEvent1; Trace.WriteLine("Subscribe 1!"); }
            if ((mask & EventType.Event2) == EventType.Event2) { m_Event2 += subscriber.OnEvent2; Trace.WriteLine("Subscribe 2!"); }
            if ((mask & EventType.Event3) == EventType.Event3) { m_Event3 += subscriber.OnEvent3; Trace.WriteLine("Subscribe 3!"); }
        }
        public void Unsubscribe(EventType mask)
        {
            IPublisherAndSubscriberCallback subscriber = OperationContext.Current.GetCallbackChannel<IPublisherAndSubscriberCallback>();
            if ((mask & EventType.Event1) == EventType.Event1) { m_Event1 -= subscriber.OnEvent1; Trace.WriteLine("Subscribe 1!"); }
            if ((mask & EventType.Event2) == EventType.Event2) { m_Event2 -= subscriber.OnEvent2; Trace.WriteLine("Subscribe 2!"); }
            if ((mask & EventType.Event3) == EventType.Event3) { m_Event3 -= subscriber.OnEvent3; Trace.WriteLine("Subscribe 3!"); }
        }
        public static void FireEvent(EventType eventType)
        {
            switch (eventType)
            {
                case EventType.Event1: m_Event1(); Trace.WriteLine("S 1!"); return;
                case EventType.Event2: m_Event2(42); Trace.WriteLine("S 2!"); return;
                case EventType.Event3: m_Event3(42, "Hello"); Trace.WriteLine("S 3!"); return;
                default: throw new InvalidOperationException("Unknown event type");
            }
        }
        public void DoSomething()
        {
            Trace.WriteLine("DoSomething");
            FireEvent(EventType.Event3);
        }
    }
}
